package com.tinem.platform.module.starter.jms.util;

import com.tinem.platform.module.starter.jms.enums.TopicEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.*;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className JmsUtil
 * @description
 * @site
 * @company
 * @create 2021-11-08 14:16
 */
@Slf4j
public abstract class JmsUtil {

    @Value("${spring.profiles.active}")
    protected String active;

    @Autowired
    protected JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * 发送消息
     * @param t topic
     * @param body
     * @return
     */
    public abstract void sendMessage(String body,String applicationName,TopicEnum t,String... args);

    /**
     * 发送延迟消息
     * @param t toptic
     * @param body
     * @param delay
     * @return jmsMessageID
     */
    public void sendMessage(String body, Long delay,String applicationName,TopicEnum t,String... args){
        String topic = t.getTopic(active,applicationName,args);
        log.info("send mq delay message:({}):({}):",topic,delay,body);

        //获取连接工厂
        ConnectionFactory connectionFactory = this.jmsMessagingTemplate.getConnectionFactory();
        try {
            //获取连接
            Connection connection = connectionFactory.createConnection();
            connection.start();
            //获取session
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Destination destination = getDestination(session,topic);
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            TextMessage message = session.createTextMessage(body);
            //设置延迟时间
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
            //发送
            producer.send(message);
            session.commit();
            producer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected abstract Destination getDestination(Session session,String topic) throws JMSException;
}
